/***********************************************************************
 * This file is part of iDempiere ERP Open Source                      *
 * http://www.idempiere.org                                            *
 *                                                                     *
 * Copyright (C) Contributors                                          *
 *                                                                     *
 * This program is free software; you can redistribute it and/or       *
 * modify it under the terms of the GNU General Public License         *
 * as published by the Free Software Foundation; either version 2      *
 * of the License, or (at your option) any later version.              *
 *                                                                     *
 * This program is distributed in the hope that it will be useful,     *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of      *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the        *
 * GNU General Public License for more details.                        *
 *                                                                     *
 * You should have received a copy of the GNU General Public License   *
 * along with this program; if not, write to the Free Software         *
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,          *
 * MA 02110-1301, USA.                                                 *
 *                                                                     *
 * Contributors:                                                       *
 * - Yang.Yu                         								   *
 **********************************************************************/
package cn.idempiere.process.lcn;

import java.util.List;
import org.compiere.model.MAcctSchema;
import org.compiere.model.MConversionType;
import org.compiere.model.MGLCategory;
import org.compiere.model.MInfoColumn;
import org.compiere.model.MSequence;
import org.compiere.model.MWarehouse;
import org.compiere.model.Query;
import org.compiere.model.X_AD_Language;
import org.compiere.model.X_AD_Ref_List;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.compiere.process.SvrProcess;

import org.adempiere.base.annotation.Process;
import org.adempiere.base.annotation.Parameter;

/**
 * Further Chinese initialization for areas not modifiable via language packs.
 * @author Yang.Yu
 */
@Process
public class InitialTenantData extends SvrProcess{

	@Parameter
	private boolean	p_isInitialConfig = true;
	@Parameter
	private boolean	p_isInitialMaster = true;
	@Parameter
	private boolean	p_isInitialTrx = true;

	private boolean isSysTenant = false;

	/**
	 *  Prepare - e.g., get Parameters.
	 */
	@Override
	protected void prepare() {
		
		isSysTenant = (Env.getAD_Client_ID(getCtx()) < MSequence.INIT_NO);

	}	//	prepare
	
	@Override
	protected String doIt() throws Exception {
		
		if (isSysTenant) { 
			initTrlConversionType();
			initTrlInfowindows();
			initTrlADInfo();
		} else {
			if (p_isInitialConfig) {
				initBaseInfo();
				initTrlGLCategory();
				initTrlDoctype();
			}
			if (p_isInitialMaster) {
				initWarehouse();
			}
			if (p_isInitialTrx) {
				;
			}
		}	
		return "@Ok@";
	}

	private boolean initBaseInfo() {
		/*
		MClient client = MClient.get(Env.getAD_Client_ID(getCtx()));
		client.setIsMultiLingualDocument(true);
		client.setAD_Language(Env.getAD_Language(getCtx()));
		client.save();
		*/
		String update = "UPDATE AD_Client SET ismultilingualdocument = 'Y' WHERE AD_Client_ID = ?";
		DB.executeUpdateEx(update,
				new Object[]{Env.getAD_Client_ID(getCtx())},
				this.get_TrxName());
		
		return true;
	}
	
	private boolean initTrlGLCategory() {
		List<MGLCategory> gls = new Query(getCtx(),MGLCategory.Table_Name, null, get_TrxName())
				.setClient_ID(true)
				.setOnlyActiveRecords(true)
				.list();
		for (MGLCategory gl : gls) {
			String name = gl.getName();
			switch (name) {
			case "None":
				gl.setName("无");
				break;
			case "Standard":
				gl.setName("标准");
				break;
			case "Manual":
				gl.setName("手工");
				break;
			case "AR Invoice":
				gl.setName("应收账款 - 发票");
				break;
			case "AR Receipt":
				gl.setName("应收账款 - 收款");
				break;
			case "Material Management":
				gl.setName("物料管理");
				break;
			case "AP Invoice":
				gl.setName("应付账款 - 发票");
				break;
			case "AP Payment":
				gl.setName("应付账款 - 付款");
				break;
			case "Cash/Payments":
				gl.setName("现金/付款");
				break;
			case "Manufacturing":
				gl.setName("生产");
				break;
			case "Distribution":
				gl.setName("分销");
				break;
			case "Payroll":
				gl.setName("工资");
				break;
			default:
				;
			}
			gl.saveEx();			
		}
		return true;
	}

	private boolean initTrlDoctype() {
		String params[][] = {
				{"AP CreditMemo","应付贷项通知单","应付贷项通知单"},
				{"AP Invoice","应付发票","应付发票"},
				{"AP Payment","付款单","付款单"},
				{"AR Credit Memo","应收贷项通知单","应收贷项通知单"},
				{"AR Pro Forma Invoice","应收形式发票","应收形式发票"},
				{"AR Invoice","应收发票","应收发票"},
				{"AR Invoice Indirect","间接应收发票","间接应收发票(POS)"},
				{"AR Receipt","收款单","收款单"},
				{"Allocation","支付分配单","支付分配单"},
				{"Bank Statement","银行对账单","银行对账单"},
				{"Cash Journal","现金日记账","现金日记账"},
				{"Distribution Order","分销订单","分销订单"},
				{"Fixed Assets Addition","资产新增单","资产新增单"},
				{"Fixed Assets Disposal","资产处置单","资产处置单"},
				{"Fixed Assets Depreciation","资产折旧单","资产折旧单"},
				{"GL Document","总账单据","总账单据"},
				{"GL Journal","凭证","凭证"},
				{"GL Journal Batch","凭证批","凭证批"},
				{"Payroll","薪酬单","薪酬单"},
				{"Manufacturing Cost Collector","制造成本归集单","制造成本归集单"},
				{"Cost Adjustment","成本调整单","成本调整单"},
				{"Internal Use Inventory","内部领用单","内部领用单"},
				{"Physical Inventory","库存调整单","库存调整单"},
				{"Material Movement","调拨单","调拨单"},
				{"Material Production","材料生产单","材料生产单"},
				{"MM Customer Return","销售退货单","销售退货单"},
				{"MM Receipt","收货单","收货单"},
				{"MM Shipment","发货单","发货单"},
				{"MM Shipment Indirect","间接发货单","间接发货单(POS)"},
				{"MM Vendor Return","采购退货单","采购退货单"},
				{"Maintenance Order","维护工单","维护工单"},
				{"Manufacturing Order","生产工单","生产工单"},
				{"Quality Order","质检单","质检单"},
				{"Match Invoice","发票匹配单","发票匹配单"},
				{"Match PO","采购匹配单","采购匹配单"},
				{"Project Issue","项目投放单","项目投放单"},
				{"Purchase Order","采购订单","采购订单"},
				{"Vendor Return Material","采购退货授权","采购退货授权"},
				{"Purchase Requisition","请购单","请购单"},
				{"Binding offer","报价单","报价单"},
				{"Credit Order","信用订单","信用订单"},
				{"Customer Return Material","销售退货授权","销售退货授权"},
				{"Non binding offer","销售建议","销售建议"},
				{"POS Order","POS订单","POS订单"},
				{"Prepay Order","预付款订单","预付款订单"},
				{"Standard Order","标准订单","标准订单"},
				{"Warehouse Order","库存订单","库存订单"}
		};
		
		String update = "UPDATE C_Doctype_Trl SET name = ? ,printname = ? WHERE AD_Client_ID = ? AND AD_Language = ? AND name = ?";
		for (int i = 0; i < params.length ; i++ ) {
			DB.executeUpdateEx(update,
							new Object[]{params[i][1],params[i][2],Env.getAD_Client_ID(getCtx()),Env.getAD_Language(this.getCtx()),params[i][0]},
							this.get_TrxName());
		}
		return true;
	}
	
	private boolean initWarehouse() {
		String lang = Env.getAD_Language(this.getCtx());
		String defaultName = Msg.translate(lang, "Standard");
		
		String sql = "SELECT M_WareHouse_ID FROM M_Warehouse wh "+
				 "WHERE wh.AD_Client_ID = ? AND wh.value = ?"; // AND wh.M_ReserveLocator_ID IS NULL
	
		int warehouseID = DB.getSQLValueEx(get_TrxName(), sql, Env.getAD_Client_ID(getCtx()),defaultName);
		MWarehouse wh = new MWarehouse(this.getCtx(),warehouseID, get_TrxName());
		if ( wh.getM_ReserveLocator_ID() == 0 ) {
			wh.setM_ReserveLocator_ID(wh.getDefaultLocator().get_ID());
			wh.saveEx();
		}
		return true;
	}
	
	private boolean initTrlConversionType() {
		Object params[][] = {
				{MConversionType.TYPE_SPOT,"即期汇率","即期汇率类型"},
				{MConversionType.TYPE_PERIOD_END,"期末汇率","期末汇率类型"},
				{MConversionType.TYPE_AVERAGE,"平均汇率","平均汇率类型"},
				{MConversionType.TYPE_COMPANY,"公司汇率","公司汇率类型"}
		};
		for (int i = 0; i < params.length ; i++ ) {
			MConversionType ct = new MConversionType(this.getCtx(),(int)params[i][0], get_TrxName());
			ct.setName((String)params[i][1]);
			ct.setDescription((String)params[i][2]);
			ct.saveEx();
		}
		return true;
	}

	// 需同步词条、重置缓存
	private boolean initTrlInfowindows() {
		
		int params[][] = {{200050,1555},{200062,1555},{200090,1555},{200020,1347},{200032,153} };
		for (int i = 0; i < params.length ; i++ ) {
			MInfoColumn infoCol = new MInfoColumn(this.getCtx(),params[i][0], get_TrxName());
			//infoCol.set_ValueOfColumn(I_AD_InfoColumn.COLUMNNAME_AD_Element_ID, params[i][1]);
			infoCol.setAD_Element_ID(params[i][1]);
			infoCol.save();
		}			
		return true;
	}
	
	private boolean initTrlADInfo() {
		// AD_Language
		X_AD_Language es_CO = new X_AD_Language(this.getCtx(),136,get_TrxName());
		es_CO.setIsSystemLanguage(false);
		es_CO.setIsLoginLocale(false);
		es_CO.save();
		
		X_AD_Language zh_CN = new X_AD_Language(this.getCtx(),187,get_TrxName());
		zh_CN.setDatePattern("yyyy-MM-dd");
		zh_CN.setTimePattern("HH:mm:ss");
		zh_CN.setAD_PrintPaper_ID(102/*A4 Portrait*/);
		zh_CN.save();
				
		// C_AcctSchema GAAP
		int refListID = 0;
		Query query = new Query(Env.getCtx(), X_AD_Ref_List.Table_Name, "AD_Reference_ID=? AND value=?", null);
		query.setOnlyActiveRecords(true);
		query.setParameters(new Object[] { MAcctSchema.GAAP_AD_Reference_ID,"CN"} );
		
		if (query.getIDs().length > 0) {
			refListID = query.getIDs()[0];
		} else {
			X_AD_Ref_List refList = new X_AD_Ref_List(getCtx(),0,get_TrxName());
			refList.setAD_Reference_ID(MAcctSchema.GAAP_AD_Reference_ID);
			refList.setValue("CN");
			refList.setName("China Accounting Standards");
			refList.setDescription("China Accounting Standards");
			refList.setEntityType("LCN");
			refList.save();
			refListID = refList.get_ID();
		}

		String update = "UPDATE AD_Ref_List_Trl SET name = ?,description = ?,istranslated = 'Y' WHERE AD_Client_ID = 0 AND AD_Language = 'zh_CN' AND AD_Ref_List_ID = ?";
		DB.executeUpdateEx(update,
						new Object[]{"中国会计准则(CAS)","中国会计准则(CAS)",refListID},
						this.get_TrxName());
		return true;
	}
}
